import { forwardRef, useImperativeHandle, useRef, useMemo, useState } from 'react';
import { inbiz } from '@inbiz/core';
import { connect, mapProps, observer } from '@formily/react';
import { useEvents, InbizIcon } from '@inbiz/utils';
import { TextWidget, RenderDropableWidget, useLayouts } from '@inbiz/react';
import BizHeader from '@inbiz/basic/BizHeader';
import BizBody from '@inbiz/basic/BizBody';
import SearchResultMain from './components/main';
import EventContext from '../common/EventContext';
import useConfigApi from '../common/useConfigApi';
import { formatPorps } from '../common/formatPorps';
import api from '../common/api';
import './style.less';
import './index.less';
import type { defaultProps } from '../../designer/schema';
import type { ISearchResultMainRef } from '../common/useConfigs';
import type { ISearchResultData } from '../../../SearchEngine/store/hooks/useJumpResult';
import type { ForwardedRef, ReactElement } from 'react';
export type IConfigItemEngineProps = {
  emit: {
    (
      key: 'onClick',
      type: 'resultItem',
      props: { data: object; event: any; IndexName: string },
    ): void; // 点击数据
    (key: 'onClick', type: 'synonymWordItem', props: { data: object; IndexName: string }): void; // 点击相似结果
    (
      key: 'onSelect',
      props: { data: object; selected: boolean; selectedAll: object[]; IndexName: string },
    ): void; //复选框状态变更
    (key: 'onSelectClear', IndexName: string): void; //复选框清空
    (key: 'onSearchData', data: ISearchResultData): void; // 搜索入口的数据
  };
  callBackEvents: {
    onSearchParams?: <T>(params: T) => Promise<T>; //搜索参数,
    onSearch?: (params: object) => Promise<object>; // 搜索接口，
    onSearchData?: <T>(data: T, params: unknown) => Promise<T>; // 搜索结果
    onSystemTypeParams?: (params: string) => Promise<string>; // 系统分类参数
    onSystemType?: (params: string) => Promise<object>; //系统分类自定义请求
    onSystemTypeData?: <T>(data: T, params: unknown) => Promise<T>; //系统分类结果
    onSynonymWordParams?: <T>(params: T) => Promise<T>; //搜索相似参数,
    onSynonymWord?: (params: object) => Promise<object>; // 搜索相似接口，
    onSynonymWordData?: <T>(data: T, params: unknown) => Promise<T>; // 搜索相似结果
    onRenderItem?: (props: {
      data: object;
      columnField: object[];
      type: 'list' | 'thumbnail';
      IndexName: string;
      checked?: boolean;
      config: object;
      setTag: any;
      dataList: any
    }) => string; // 自定义渲染项
    onRenderBody?: (props: {
      showStyle?: string;
      dataSoure?: object[];
      config?: object;
      selected?: object;
      uniqueKey?: string;
      onSelect?: Function;
      loading?: boolean;
      emit: Function;
      inbiz: any;
    }) => ReactElement;
    onGetBack: () => void,
    searchKeyword: () => string,
    setFilterNumber: (val: number) => number
  };
  displayRule: '1' | '2';
  inbiz: inbiz;
  controlId: string;
  boxHeight: string;
  style: CSSStyleSheet;
} & typeof defaultProps;

function SearchResultEngine(
  props: IConfigItemEngineProps,
  ref: ForwardedRef<ISearchResultMainRef>,
) {
  const [configEvents] = useEvents(props.callBackEvents);
  const configEventsApi = useConfigApi(configEvents);
  const refMain = useRef<ISearchResultMainRef>(null);
  const [searchKeyword, $searchKeyword] = useState('')
  useImperativeHandle(ref, () => api(configEvents, refMain), []);
  const getBack = () => {
    if (configEvents.current?.onGetBack) {
      configEvents.current?.onGetBack()
    }
  }

  return (
    <EventContext.Provider
      value={{ configEvents, configEventsApi, emit: props.emit || (() => { }), inbiz: props.inbiz }}
    >
      <div className="searchResultEngine" style={{ height: props.boxHeight }}>
        <BizHeader {...props} />
        <BizBody style={props.style}>
          <div className='backHeader' style={{ display: 'flex' }}>
            {props.showBack && <div className='backButton' onClick={getBack}><InbizIcon type='icon-ic-zuofan' style={{ color: '#999', marginRight: 5 }} /><TextWidget>SearchResultEngine.back</TextWidget></div>}
            {searchKeyword && <div style={{ cursor: 'pointer', height: 20, lineHeight: '20px' }}>
              <span style={{ color: '#ea4d3e' }} title={searchKeyword}>"{searchKeyword.length > 20 ? searchKeyword.slice(0, 20) + '...' : searchKeyword}"  </span>
              <span><TextWidget>SearchResultEngine.deReasult</TextWidget></span>
            </div>}
          </div>
          <SearchResultMain $searchKeyword={$searchKeyword} configs={props.indexIibraryConfig} engineProps={props} ref={refMain} />
        </BizBody>
      </div>
    </EventContext.Provider>
  );
}
const SearchResult = connect(forwardRef(SearchResultEngine), mapProps({}, formatPorps));

SearchResult['Plugin'] = (props: any) => {
  const { align, direction, className } = props;
  return (
    <div
      className={`searchResultEngine-PluginBox ${className || ''}`}
      style={{
        flexDirection: direction || 'row',
        justifyContent: align || 'center',
        alignItems: align || 'center',
      }}
    >
      {props.children}
    </div>
  );
};

SearchResult['RightPlugin'] = (props: any) => {
  return (
    <div>
      {props.children}
    </div>
  );
};

SearchResult['CenterPlugin'] = (props: any) => {
  const { align, direction, className } = props;
  return (
    <div
      className={`searchResultEngine-CenterPlugin ${className || ''}`}
      style={{
        display: 'flex',
        flexDirection: direction || 'row',
        justifyContent: align || 'center',
        alignItems: align || 'center',
      }}>
      {props.children}
    </div>
  );
};

export const ShowPlugin = ({ IndexCode, pluginName }: { IndexCode: string, pluginName: string }) => {
  const layouts = useLayouts(pluginName);
  const index = useMemo(() => {
    let number = layouts.findIndex((item) => item.props.IndexCode == IndexCode);
    if (number != -1) {
      // 没有子节点时， 不显示
      if (!Object.keys(layouts?.[number]?.schema?.properties || {})?.length) {
        number = -1;
      }
    }
    return number;
  }, [IndexCode, layouts]);

  if (index >= 0) {
    return <RenderDropableWidget pluginName={pluginName} pluginIndex={index} />;
  } else {
    return null;
  }
};
export default SearchResult;
